import json
import asyncio
from asyncio import Task
from typing import Optional

from app.store import Store
from logging import getLogger
from app.store.broker.producer import new_task

import os
import mysql.connector

def messages_db(update: dict) -> None:
    config = {
        'user': os.environ.get('MYSQL_USER'),
        'password': os.environ.get('MYSQL_ROOT_PASSWORD'),
        'host': os.environ.get('MYSQL_HOST'),
        'port': os.environ.get('MYSQL_PORT'),
        'database': 'chat_bot'
    }
    connection = mysql.connector.connect(**config)
    cursor = connection.cursor()
    query = f"INSERT INTO messages (from_username, msg_text) VALUES ('{update['message']['from']['username']}', '{update['message']['text']}')"
    cursor.execute(query)
    connection.commit()
    cursor.close()
    connection.close()

class Poller:
    def __init__(self, store: Store):
        self.store = store
        self.logger = getLogger("poller")
        self.is_running = False
        self.poll_task: Optional[Task] = None

    async def start(self):
        self.logger.info("start polling")
        self.is_running = True
        self.poll_task = asyncio.create_task(self.poll())

    async def stop(self):
        # TODO отловить завершение через KeyboardInterrupt и корректно завершить работу бота
        self.logger.info("stop polling")
        self.is_running = False
        await self.poll_task


    async def poll(self):
        offset = 0
        while self.is_running:
            updates = await self.store.tg_api.get_updates(offset=offset, timeout=60)
            for upd in updates["result"]:
                messages_db(upd)
                task = json.dumps(upd)
                new_task(task)
                offset = upd["update_id"] + 1
